package com.github.hiling.gateway.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.hiling.common.exception.BusinessException;
import com.github.hiling.common.exception.ExceptionResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.ConnectException;

/**
 * 网关全局异常处理
 * @author javadaily
 */
@Slf4j
@Order(-1)
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class GlobalErrorWebExceptionHandler implements ErrorWebExceptionHandler {
    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        ServerHttpRequest request = exchange.getRequest();

        HttpStatusCode httpStatusCode;
        // 设置返回JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (ex instanceof ResponseStatusException) {
            httpStatusCode = ((ResponseStatusException) ex).getStatusCode();
            response.setStatusCode(httpStatusCode);
        } else if (ex instanceof BusinessException) {
            httpStatusCode = HttpStatus.BAD_REQUEST;
        } else if (ex instanceof ConnectException) {
            httpStatusCode = HttpStatus.GATEWAY_TIMEOUT;
        } else {
            httpStatusCode = HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                //返回响应结果
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(new ExceptionResult(httpStatusCode.value(), ex.getMessage(), getStackTrace(ex.getStackTrace()), getUri(request))));
            } catch (JsonProcessingException e) {
                log.error("Error writing response", ex);
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }

    private String getUri(ServerHttpRequest request) {
        String queryString = request.getURI().getQuery();
        return request.getMethod() + ":" + request.getURI().getPath()
                + (StringUtils.isEmpty(queryString) ? "" : ("?" + queryString));
    }

    private String getStackTrace(StackTraceElement[] element) {
        String stackTrace = null;
        //堆栈信息
        if (element != null && element.length > 0) {
            stackTrace = element[0].toString();
        }
        return stackTrace;
    }
}